package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.config.JwtProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final JwtProperties jwtProperties;
    private final JwtTool jwtTool;
    //路径判断看是否包含什么字符
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.判断是否要进行登录的请求，有些页面是不需要登录，就能实现的。（例如：登录页面，搜索商品页面）。
        ServerHttpRequest request = exchange.getRequest();
        if(isExclude(request.getPath().toString())) {
            //有些页面是不需要登录，就能实现的。（例如：登录页面，搜索商品页面）
            return chain.filter(exchange);
        }
        //2.如果要登录：获取请求头的属性authorization的值就是令牌。
        String token = request.getHeaders().getFirst("Authorization");
        //3.校验令牌：获得用户信息。
        try {
            Long userId = jwtTool.parseToken(token);
            //4.将用户信息传递给后端微服务。
            System.out.println("用户id：" + userId);
            //将用户id设置到请求头中
            exchange.mutate().request(builder -> {
                builder.header("user-info", userId.toString());
            }).build();
                    //改写request对象，设置请求头到后端微服务
        } catch (Exception e) {
            //校验不通过则返回，没有授权：401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //校验通过则放行。
        return chain.filter(exchange);
    }

    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()){
            //判断是否是排除路径
            if(antPathMatcher.match(excludePath, path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
